package com.login.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.login.entity.User;
import com.login.resp.LoginUserResp;
import com.login.service.UserService;
import com.login.utils.ResponseResult;
import com.login.utils.enums.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Locale;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    UserService userService;

    HashMap<Integer,Object> loginUsers = new HashMap<>();

    @PostMapping("/login")
    public ResponseResult login(String username,String password){
        //保存已经登录的用户
        User user = userService.login(username,password);
        if(user == null){
            return new ResponseResult(ResultCodeEnum.LOGIN_FAIL);
        }else{
            //token - 凭证
            String token = IdUtil.simpleUUID().toUpperCase(Locale.ROOT);
            log.info("生成token:{}",token);
            LoginUserResp userResp = new LoginUserResp();
            BeanUtil.copyProperties(user,userResp);
            userResp.setToken(token);
            loginUsers.put(user.getUserId(),user);
            return new ResponseResult(userResp);
        }
    }

    @PostMapping("/logout")
    public ResponseResult logout(int userId){
        loginUsers.remove(userId);
        return new ResponseResult();
    }

    @PostMapping("/delete")
    public ResponseResult deleteUser(int id,int userId){
        if (loginUsers.containsKey(userId)) {
            System.out.println("当前操作用户:"+userId+",删除id:"+id);
            return new ResponseResult();
        }else{
            return new ResponseResult(ResultCodeEnum.AUTH_FAIL);
        }

    }
}
